package com.JFapp.controller;


import com.JFapp.annotation.validator.group.register;
import com.JFapp.domain.entity.LoginUser;
import com.JFapp.domain.entity.Menu;
import com.JFapp.domain.entity.ResponseResult;

import com.JFapp.domain.entity.User;
import com.JFapp.domain.vo.AdminUserInfoVo;
import com.JFapp.domain.vo.PasswordVo;
import com.JFapp.domain.vo.RoutersVo;
import com.JFapp.domain.vo.UserInfoVo;
import com.JFapp.eumns.AppHttpCodeEnum;
import com.JFapp.exception.SystemException;
import com.JFapp.service.LoginService;
import com.JFapp.service.MenuService;
import com.JFapp.service.RoleService;
import com.JFapp.service.UserService;
import com.JFapp.utils.BeanCopyUtils;
import com.JFapp.utils.JwtUtil;
import com.JFapp.utils.RedisCache;
import com.JFapp.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RestController
@Api(tags = "后台登陆")
public class AdminLoginController {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LoginService loginService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @ApiOperation("登录")
    public ResponseResult login(@RequestBody User user){
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }


    @ApiOperation("获取用户权限")
    @GetMapping("/getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
        //获取当前的登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //根据用户id查询权限信息
        List<String> perms= menuService.selectPermByUserId(loginUser.getUser().getId());
        //根据用户id查询角色信息
        List<String> roleKeyList= roleService.selectRoleKeyListByUserId(loginUser.getUser().getId());
        //获取用户信息
        User user = loginUser.getUser();
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        //封装返回
        AdminUserInfoVo vo= new AdminUserInfoVo(perms,roleKeyList,userInfoVo);
        return ResponseResult.okResult(vo);
    }

    @ApiOperation("查找目录")
    @GetMapping("/getRouters")
    public ResponseResult<RoutersVo> getRouters(){
        //获取当前用户
        Long userId = SecurityUtils.getUserId();
        //获取menu，结果为tree形式
        List<Menu> menu=menuService.selectRoutersMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RoutersVo(menu));
    }

    @ApiOperation("发送重置邮件")
    @PostMapping("/resetPassword")
    public ResponseResult resetPassword(@RequestParam("email") String email, HttpServletRequest httpServletRequest){
        User user = userService.findUserByEmail(email);
        if (user==null){
            throw new RuntimeException(AppHttpCodeEnum.NOT_FIND_USER.getMessage());
        }
        return loginService.resetPassword(user);
    }

//    @ApiOperation("重置链接")
//    @GetMapping("/changePassword")
//    public String ChangePasswordPage(@Param("token") String token) {
//        String id;
//        try {
//            Claims claims = JwtUtil.parseJWT(token);
//            String s = claims.getSubject();
//            id = claims.getId();
//            redisCache.setCacheObject("reset" + id, s);
//        } catch (Exception e) {
//            throw new RuntimeException(AppHttpCodeEnum.OUT_OF_TOKEN);
//        }
//        return "redirect:/changePassword/toChange?id=" + id;
//    }

    @PostMapping("/changePassword/toChange")
    @ApiOperation("重置界面")
    public ResponseResult change(@RequestBody PasswordVo password){
        if (Objects.equals(password.getPassword(), password.getNpassword())){
          return  loginService.changePassword( password.getPassword(), password.getResetToken());
        }else {
            throw new RuntimeException(AppHttpCodeEnum.CHECK_PASSWORD);
        }
    }


    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public ResponseResult register( @RequestBody @Validated(register.class) User user){
        return userService.register(user);
    }
}
